package com.hznc.wcs.flowable.candidate;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.diboot.iam.entity.IamUser;
import com.diboot.iam.service.IamUserService;

import com.hznc.wcs.enums.BpmTaskCandidateStrategyEnum;
import com.hznc.wcs.exception.BusinessException;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 用户 {@link BpmTaskCandidateStrategy} 实现类
 *
 * @author kyle
 */
@Component
public class BpmTaskCandidateUserStrategy implements BpmTaskCandidateStrategy {

    @Resource
    private IamUserService iamUserService;

    @Override
    public BpmTaskCandidateStrategyEnum getStrategy() {
        return BpmTaskCandidateStrategyEnum.USER;
    }

    @Override
    public void validateParam(String param) {
        String[] userIdAndUserNum = StringUtils.split(param, ",");
        List<String> list = Arrays.asList(userIdAndUserNum);
        List<String> userIdList = list.stream().map(item -> item.split("#")[0]).toList();
//        List<String> userIdList = Arrays.asList(StringUtils.split(param,","));
        for (String userId:userIdList){
            LambdaQueryWrapper<IamUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(IamUser::getId,userId);
            boolean exists = iamUserService.exists(queryWrapper);
            if (!exists){
                throw new BusinessException("用户不存在");
            }
        }
    }

    @Override
    public Set<String> calculateUsers(DelegateExecution execution, String param) {
        String[] userIdAndUserNum = StringUtils.split(param, ",");
        List<String> list = Arrays.asList(userIdAndUserNum);
        List<String> userIdList = list.stream().map(item -> item.split("#")[0]).toList();
        return new HashSet<>(userIdList);
    }

}